<template>
  <scroll-view :scroll-y="true" class="h-11/12 m-auto w-11/12">
    <uni-forms :modelValue="formData">
      <!-- 使用部门 -->
      <uni-card title="使用部门" extra="必填*">
        <uni-forms-item>
          <uni-easyinput v-model="formData.shiYongBuMen" :disabled="isEdit" />
        </uni-forms-item>
      </uni-card>
      <!-- 使用中的食品添加剂名称 -->
      <uni-card title="使用中的食品添加剂名称" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.shiYongZhongDeShiPinTianJiaJiMingCheng"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <!-- 使用中的食品添加剂名称图片 -->
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.shiYongZhongDeShiPinTianJiaJiMingChengImg"
            mode="grid"
            @select="upload"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 制备的食品品种 -->
      <uni-card title="制备的食品品种" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            type="textarea"
            v-model="formData.zhiBeiDeShiPinPinZhong"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 规定使用量 -->
      <uni-card title="规定使用量" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.guiDingShiYongLiang"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 填报人姓名 -->
      <uni-card title="填报人姓名" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.tianBaoRenXingMing"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <uni-card title="评语" v-show="props.id">
        <uni-easyinput v-model="reviewOpinion" />
      </uni-card>
    </uni-forms>
    <button
      @click="submitForm"
      class="mb-10 w-2/3 rounded-xl"
      style="background-color: #5199ff"
    >
      {{ submitBtnName }}
    </button>
    <ShowConfigComponent
      v-show="!isEdit"
      name="tianJiaJiQingDan"
      @showFormData="showFormData"
    />
  </scroll-view>
</template>

<script lang="ts" setup>
import { submitMenuIdList } from '@/services/review';
import type { RequestMenuIdList } from '@/services/types/review';
import type {
  FormDetail,
  returnSubmitData,
  submitTableData,
  tableDate,
} from '@/services/types/write';
import { createTableById, showTableById, submitTable } from '@/services/write';
import { uploadImg } from '@/utils/http';
import { convertToString, compareLoadData, transformData } from '@/utils/utils';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';

// 表格提交信息
const formData = ref({
  shiYongBuMen: '', // 使用部门
  shiYongZhongDeShiPinTianJiaJiMingCheng: '', // 使用中的食品添加剂名称
  shiYongZhongDeShiPinTianJiaJiMingChengImg: [] as {
    url: string;
    extname: string;
    name: string;
  }[], // 使用中的食品添加剂名称图片
  zhiBeiDeShiPinPinZhong: '', // 制备的食品品种
  guiDingShiYongLiang: '', // 规定使用量
  tianBaoRenXingMing: '', // 填报人姓名
});
const props = defineProps({
  value: String,
  id: String,
});
// 评语
const reviewOpinion = ref('');
// 是否可编辑
const isEdit = ref(false);
// 提交按钮名字
const submitBtnName = ref('');
// 上传图片
const upload = (e: UniHelper.PickerInstance) => {
  uploadImg(e).then((res) => {
    formData.value.shiYongZhongDeShiPinTianJiaJiMingChengImg.push({
      url: res.url,
      extname: 'jpg',
      name: res.key,
    });
  });
};
/**
 * 表格相关数据
 */
const table = () => {
  const tableData = ref<tableDate[]>([]);
  const reportingFormOperateId = ref('');
  // 如果提交按钮等于提交则创建表格
  const createTable = async () => {
    submitBtnName.value = '提交';
    // 创建表格
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    const res = await createTableById('8286264035435151360');
    reportingFormOperateId.value = res.reportingFormOperateId;
    tableData.value = res.data;
    uni.hideLoading();
  };
  // 提交表格
  const submitNewTable = (
    reportingFormOperateId: string,
    tableData: tableDate[],
  ): submitTableData => {
    const formDetail = transformData(tableData) as FormDetail[];
    // 使用部门
    formDetail[0].componentValue = formData.value.shiYongBuMen;
    // 使用中的食品添加剂名称
    formDetail[1].componentValue =
      formData.value.shiYongZhongDeShiPinTianJiaJiMingCheng;
    // 使用中的食品添加剂名称图片
    if (formData.value.shiYongZhongDeShiPinTianJiaJiMingChengImg.length) {
      formDetail[2].componentValue = convertToString(
        formData.value.shiYongZhongDeShiPinTianJiaJiMingChengImg as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    // 制备的食品品种
    formDetail[3].componentValue = formData.value.zhiBeiDeShiPinPinZhong;
    // 规定使用量
    formDetail[4].componentValue = formData.value.guiDingShiYongLiang;
    // 填报人姓名
    formDetail[5].componentValue = formData.value.tianBaoRenXingMing;
    // 其他数据
    const submitTable = ref<submitTableData>({
      formDetail: formDetail,
      reportingFormOperateId: reportingFormOperateId,
      status: 1,
      unionMenuId: '8286264035435151360',
    });

    return submitTable.value;
  };
  return {
    createTable,
    tableData,
    reportingFormOperateId,
    submitNewTable,
  };
};
const { createTable, submitNewTable, tableData, reportingFormOperateId } =
  table();
// 根据id展示数据
const showDataById = async (id: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await showTableById(id);
  if (res.msg === 'success') {
    // 使用部门
    formData.value.shiYongBuMen = res.data.formDetail[0].componentValue;
    // 使用中的食品添加剂名称
    formData.value.shiYongZhongDeShiPinTianJiaJiMingCheng =
      res.data.formDetail[1].componentValue;
    // 使用中的食品添加剂名称图片
    if (res.data.formDetail[2].tfiles) {
      formData.value.shiYongZhongDeShiPinTianJiaJiMingChengImg = [];
      res.data.formDetail[2].tfiles.map((item) => {
        formData.value.shiYongZhongDeShiPinTianJiaJiMingChengImg.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    // 制备的食品品种
    formData.value.zhiBeiDeShiPinPinZhong =
      res.data.formDetail[3].componentValue;

    // 规定使用量
    formData.value.guiDingShiYongLiang = res.data.formDetail[4].componentValue;

    // 填报人姓名
    if (res.data.formDetail[5]) {
      formData.value.tianBaoRenXingMing = res.data.formDetail[5].componentValue;
    }
    // 评语
    reviewOpinion.value = (
      res.data as returnSubmitData
    ).handleOption.reviewOpinion;
  }
  uni.hideLoading();
};
onLoad(async () => {
  // 判断提交按钮是否等于newTable，
  // 等于newTable则执行创建表格
  if (props.value === 'newTable') {
    createTable();
  } else if (props.id) {
    showDataById(props.id);
    submitBtnName.value = '审批';
    isEdit.value = true;
  }
});
// 提交
const submitForm = () => {
  uni.showModal({
    title: '确认提交？',
    content: '提交后将无法修改，请确认是否提交',
    success: function (res) {
      if (res.confirm) {
        // 等于newTable则执行提交表格
        if (props.value === 'newTable') {
          submitTable(
            submitNewTable(reportingFormOperateId.value, tableData.value),
          ).then((res) => {
            if (res.msg === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        } else if (props.id) {
          // 有id意味查看详情
          const data = ref<RequestMenuIdList>({
            id: props.id,
          });
          submitMenuIdList(data.value, reviewOpinion.value).then((res) => {
            if (res.data === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        }
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};
// 加载配置
const showFormData = (data: any) => {
  compareLoadData(formData.value, data);
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
